﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.Models;
using JiveMessenger.User;
using JmShared;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
using JiveMessenger.Utilities;
using JiveMessenger.CustomEventArgs;
using System.Diagnostics;
using JiveMessenger.Network;
using Windows.ApplicationModel;
using JiveMessenger.CustomControls;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using JiveMessenger.Log;


namespace JiveMessenger.ViewModels
{
    [DataContract]
    public class ViewModelPrivateMessage : ViewModelChat
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private DateTime _lastNudge;
        //private IClient _currentClient;
        //private JiveContactModel _currentUser;
        public RelayCommand NudgeCommand { get; set; }
        public RelayCommand NowWritingCommand { get; set; }
        public RelayCommand<string> SendMessageCommand { get; set; }
        public RelayCommand EmoticonControlSendMessageCommand { get; set; }
        public IContact PmTarget
        {
            get
            {
                IContact contact = null;
                Messenger.Default.Send(new NotificationMessageAction<IContact>(this, PmTargetUsername, "GetContactFromUsername", cont =>
                    {
                        contact = cont;
                    }));
                return contact;
            }
        }
        [DataMember]
        public string PmTargetUsername{get;set;}

        ~ViewModelPrivateMessage()
        {
            if (DesignMode.DesignModeEnabled)
                return;
            Logger.Debug("ViewModelPrivateMessage destructed");
        }
        public ViewModelPrivateMessage(IClient currentClient, IContact model)
            : base(currentClient, model.UserName, !String.IsNullOrEmpty(model.NickName) ? model.NickName : model.UserName)
        {
            PmTargetUsername = model.UserName;
            //ViewModelName = !String.IsNullOrEmpty(model.NickName) ? model.NickName : model.UserName;
            //this._currentClient = currentClient;
            //this._currentUser = (JiveContactModel)currentUser;
            //this.ID = model.UserName;
           // this.PmTarget = model;
            if (IsInDesignMode)
            {

            }
            else
            {


                // this.IsInputTextFocused = true;
                InitializeCommands();
                RegisterMessengers();

            }

            //this.PropertyChanged += ViewModelPrivateMessage_PropertyChanged;
        }
        [OnDeserialized]
        internal void InitializePrivateMessage(StreamingContext context)
        {
            InitializeCommands();
            RegisterMessengers();
        }

        private void InitializeCommands()
        {
            this.NudgeCommand = new RelayCommand(NudgeCommandAction, () => CurrentClient.IsLoggedIn);
            this.SendMessageCommand = new RelayCommand<string>(SendMessageCommandAction, (e) => CurrentClient.IsLoggedIn);
            this.NowWritingCommand = new RelayCommand(NowWritingCommandAction, () => CurrentClient.IsLoggedIn);
            this.EmoticonControlSendMessageCommand = new RelayCommand(EmoticonControlSendMessageCommandAction, () => CurrentClient.IsLoggedIn);
        }

        private void RegisterMessengers()
        {
            Messenger.Default.Register<NotificationMessage<IContact>>(this, msg =>
            {
                switch (msg.Notification)
                {
                    case "UpdatePrivateMessage":
                        IContact contact = msg.Content;
                        if (contact.UserName == this.ID)
                        {
                            this.ViewModelName = contact.NickName;
                        }
                        break;
                }
            });

        }

        private async void EmoticonControlSendMessageCommandAction()
        {
            //   string msgText = this.InputText;

            this.IsInputTextFocused = true;
            if (await this.SendMessage(this.InputText))
                this.InputText = "";
        }



        public override void Cleanup()
        {
            base.Cleanup();
        }

        private async void SendMessageCommandAction(string msg)
        {

            if (await SendMessage(msg))
                this.InputText = "";
        }

        private async void NowWritingCommandAction()
        {
            await CurrentClient.Connection.SendMessage(new ChatMessage(CurrentClient.CurrentUserInfo.ID, CurrentClient.CurrentUserInfo.UserName, MessageType.IsWriting, "PM", PmTargetUsername));
        }
        private async void NudgeCommandAction()
        {
            if (DateTime.Now.Subtract(this._lastNudge).TotalSeconds < 5)
            {
                this.DisplayMessage(new DisplayMessage(CurrentUser, "You may not send a nudge that often.", DisplayMessageOptions.ErrorOptions, DateTime.Now, true));
                return;
            }

            ChatMessage msg = new ChatMessage(CurrentClient.CurrentUserInfo.ID, CurrentClient.CurrentUserInfo.UserName, MessageType.Nudge, "PM", PmTargetUsername);

            await CurrentClient.Connection.SendMessage(msg);

            Messenger.Default.Send(new NotificationMessage(this, "Nudge"));
            this.DisplayMessage(new DisplayMessage(CurrentUser, "You have sent a nudge!", DisplayMessageOptions.NudgeOptions, DateTime.Now, true));
            this._lastNudge = DateTime.Now;
        }


        private async Task<bool> SendMessage(string text)
        {
            if (!CurrentClient.IsLoggedIn)
                return false;
            ChatMessage msg = new ChatMessage(CurrentClient.CurrentUserInfo.ID, CurrentClient.CurrentUserInfo.UserName, MessageType.PrivateMessage, text, PmTargetUsername)
            {
                MessageID = CurrentClient.MessageID++
            };
            this.DisplayMessage(new DisplayMessage(CurrentUser, text, DisplayMessageOptions.ChatMessageOption, DateTime.Now, true));
            if (!await CurrentClient.Connection.SendMessage(msg))
            {
                if (msg.MessageType == MessageType.GroupMessage)
                    this.DisplayMessage(new DisplayMessage(CurrentUser, String.Format("Message response timeout. It is possible the message was not received: {0}", msg.Message), DisplayMessageOptions.ErrorOptions, DateTime.Now, true));
                return false;
            }
            return true;
        }
        public override void DisplayMessage(DisplayMessage displayMessage)
        {
            displayMessage.ChatTarget = PmTargetUsername;
            base.DisplayMessage(displayMessage);
        }

        //public override void DisplayMessage(IContact sender, string message, DisplayMessageOptions options, DateTime timestamp, bool isLastInBatch)
        //{

        //    DisplayMessage(new DisplayMessage(sender, message, this.PmTarget.UserName, options, timestamp, isLastInBatch));
        //    if (!IsInDesignMode)
        //    {
        //        if (options.BlinkTab && !this.IsCurrentActiveTab)//&& VmHelper.Locator.ViewModelMainWindow.CurrentActiveViewModel != this)
        //            this.IsBlinking = true;
        //    }
        //}



    }
}
